package com.igroupes.ovineherd.raw.service.raw;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.igroupes.ovineherd.entity.DataModelVersionEntity;
import com.igroupes.ovineherd.mapper.DataModelVersionMapper;
import com.igroupes.ovineherd.util.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.List;

@Slf4j
@Service
public class DataModelVersionService extends ServiceImpl<DataModelVersionMapper, DataModelVersionEntity> {

    /**
     * 获取我的最新编辑版本号
     * @param userId
     * @return
     */
    public Long getModelVersionEdit(Long userId){
        QueryWrapper<DataModelVersionEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(DataModelVersionEntity::getAddUser, userId)
                .eq(DataModelVersionEntity::getCurrentVersion, DataModelVersionEntity.EDIT)
                .orderByDesc(DataModelVersionEntity::getUpdateTime);
        List<DataModelVersionEntity> dataModelVersionEntitys = this.list(wrapper);
        //新用户，创建版本
        if(dataModelVersionEntitys.size() == 0){
            DataModelVersionEntity dataModelVersionEntity = new DataModelVersionEntity();
            dataModelVersionEntity.setAddUser(userId);
            dataModelVersionEntity.setCurrentVersion(DataModelVersionEntity.EDIT);
            dataModelVersionEntity.setName(DateUtils.getDate(DateUtils.DATETIME_FORMAT));
            dataModelVersionEntity.setPId(Convert.toLong(DataModelVersionEntity.TOPPID));
            this.save(dataModelVersionEntity);
            return dataModelVersionEntity.getId();
        }
        return dataModelVersionEntitys.get(0).getId();
    }
    /**
     * 获取我的发布版本号
     * @param userId
     * @return
     */
    public Long getModelVersionPublish(Long userId){
        QueryWrapper<DataModelVersionEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(DataModelVersionEntity::getAddUser, userId)
                .eq(DataModelVersionEntity::getCurrentVersion, DataModelVersionEntity.PUBLISH)
                .orderByDesc(DataModelVersionEntity::getUpdateTime);
        List<DataModelVersionEntity> dataModelVersionEntitys = this.list(wrapper);
        //新用户，创建版本
        if(dataModelVersionEntitys.size() == 0){
            return null;
        }
        return dataModelVersionEntitys.get(0).getId();
    }

    /**
     * 修改数据编辑过
     * @param versionId
     */
    public void hasEdit(Long versionId){
        UpdateWrapper<DataModelVersionEntity> wrapper = new UpdateWrapper<>();
        wrapper.lambda()
                .set(DataModelVersionEntity::getHasEdit, true)
                .eq(DataModelVersionEntity::getId, versionId);
        this.update(wrapper);
    }
}
